<?php

namespace app\common\model\Product;

use think\Model;
use traits\model\SoftDelete;

class Product extends Model
{
    // 软删除
    use SoftDelete;

    protected $name = 'product';
    
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    protected $append = [
        'flag_text',
        'status_text',
        'thumbs_text',
        'rent_status_text'
    ];

    public function getFlagTextAttr($value, $data)
    {
        $value = isset($data['flag']) ? $data['flag'] : '';

        $list = $this->getFlagList();

        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = isset($data['status']) ? $data['status'] : '';

        $list = $this->getStatusList();

        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getThumbsTextAttr($value, $data)
    {
        $cdnurl = config('site.cdnurl');
        // $base = config('site.url');

        $thumbs = empty($data['thumbs']) ? [] : explode(',', $data['thumbs']);

        $res = [];

        if(empty($thumbs))
        {
            return [$cdnurl .'/assets/home/images/cbd.jpg'];
        }

        foreach($thumbs as $k => $v){
            // $thumbs[$k] = $cdnurl . trim($v);

            if(is_file('.' . trim($v))){
                $res[] = $cdnurl . trim($v);
            }else{
                $res[] = $cdnurl .'/assets/home/images/cbd.jpg';
            }
        }

        return  $res;
    }

    public function getRentStatusTextAttr($value, $data)
    {
        $value = isset($data['rentstatus']) ? $data['rentstatus'] : '';

        $list = ['1' => '普通商品','2' => '仅租商品','3' => '既购买也能租赁的商品'];

        return isset($list[$value]) ? $list[$value] : '';
    }

    // 分类关联查询
    public function type()
    {
        return $this->belongsTo('app\common\model\Product\Type','typeid','id',[],'LEFT')->setEagerlyType(0);
    }

    // 单位关联查询
    public function unit()
    {
        return $this->belongsTo('app\common\model\Product\Unit','unitid','id',[],'LEFT')->setEagerlyType(0);
    }

    public function getFlagList()
    {
        return ['1' => __('新品'), '2' => __('热销'), '3' => __('推荐')];
    }

    public function getStatusList()
    {
        return ['0' => __('下架'), '1' => __('上架')];
    }
}
